//*****************************************************************************
// JFab (http://code.google.com/p/jfab)
// Copyright (c) 2011-2012 JFab.org
// Admin jfab@jeffreythompson.net
//
// See the file "LICENSE.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//*****************************************************************************

package org.jfab.core.adapter;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

/**
 * Provides an adapter for <code>List</code>.
 * <p>
 * The string format is one item per line using a line separator.
 * </p>
 * 
 * @param <E> Element type.
 */
public class ListAdapter<E> implements Adapter<List<E>>
{
    /** Line separator. */
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");

    /** Element adapter. */
    private final Adapter<E> _elementAdapter;

    /**
     * Construct this object with the given parameter.
     * 
     * @param elementAdapter Element adapter. (required)
     */
    public ListAdapter(final Adapter<E> elementAdapter)
    {
        Validate.notNull(elementAdapter);

        _elementAdapter = elementAdapter;
    }

    @Override
    public String marshal(final List<E> value)
    {
        String answer = null;

        if (CollectionUtils.isNotEmpty(value))
        {
            final StringBuilder sb = new StringBuilder();
            final int size = value.size();

            for (int i = 0; i < size; i++)
            {
                final String string = _elementAdapter.marshal(value.get(i));
                sb.append(string);

                if (i < (size - 1))
                {
                    sb.append(LINE_SEPARATOR);
                }
            }

            answer = sb.toString();
        }

        return answer;
    }

    @Override
    public List<E> unmarshal(final String value)
    {
        final List<E> answer = new ArrayList<E>();

        if (StringUtils.isNotEmpty(value))
        {
            final String[] lines = value.split(LINE_SEPARATOR);

            for (int i = 0; i < lines.length; i++)
            {
                final E element = _elementAdapter.unmarshal(lines[i]);
                answer.add(element);
            }
        }

        return answer;
    }
}
